//
//  LRUserAccount.swift
//  WeiboX
//
//  Created by admin on 03/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit

class LRUserAccount: NSObject, NSCoding {
	
	var access_token: String?
	var expires_in: TimeInterval = 0 {
		didSet {
			expiresDate = Date().addingTimeInterval(expires_in)
		}
	}
	var expiresDate: Date?
	var uid: Int64 = 0
	var name: String?
	var avatar_large: String?
	
	init(dic: [String: Any]) {
		super.init()
		
		setValuesForKeys(dic)
	}
	
	override func setValue(_ value: Any?, forUndefinedKey key: String) {
		
	}
	
	// 归档
	func encode(with aCoder: NSCoder) {
		aCoder.encode(access_token, forKey: "access_token")
		aCoder.encode(expiresDate, forKey: "expiresDate")
		aCoder.encode(uid, forKey: "uid")
		aCoder.encode(name, forKey: "name")
		aCoder.encode(avatar_large, forKey: "avatar_large")
	}
	
	// 解档
	required init?(coder aDecoder: NSCoder) {
		access_token = aDecoder.decodeObject(forKey: "access_token") as? String
		expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
		uid = aDecoder.decodeInt64(forKey: "uid")
		name = aDecoder.decodeObject(forKey: "name") as? String
		avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
	}
	
	// 保存用户对象
	func saveUserInfo() {
		let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
		NSKeyedArchiver.archiveRootObject(self, toFile: path)
	}
	
	// 加载用户对象
	class func loadUserInfo() -> LRUserAccount? {
		let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
		let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path)
		
		return userAccount as? LRUserAccount
	}
}
